$(document).ready(function (){
	
	// check box change
	$("#all").change(function(){
		if ($(this).is(':checked')){
			$('#promotion').removeAttr('checked');
		} else {
			$('#promotion').attr('checked', 'checked');
		}
	});
	$("#promotion").change(function(){
		if ($(this).is(':checked')){
			$('#all').removeAttr('checked');
		} else {
			$('#all').attr('checked', 'checked');
		}
	});
	
	// login popup
	$( "#login-dialog-form" ).dialog({
		 autoOpen: false,
		 height: 250,
		 width: 400,
		 modal: true,
		 buttons: {
			 "Đăng nhập": function() {
				 var email = $("#login-email");
				 var password = $("#login-password");
				 if (checkEmail(email , "Email") && 
						 checkEmpty(password, "mật khẩu")){
					 userLogin(email, password);
				 }
			 },
			 "Hủy bỏ": function() {
				 $( this ).dialog( "close" );
			 }
		 }
	 });
	 
	// registor popup
	 $( "#register-dialog-form" ).dialog({
		 autoOpen: false,
		 height: 300,
		 width: 400,
		 modal: true,
		 buttons: {
			 "Đăng ký": function() {
				 var email = $("#register-email");
				 var password = $("#register-password");
				 var confirm_password = $("#confirm-password");
				 if (checkEmail(email , "Email") && 
						 checkEmpty(password, "mật khẩu") &&
						 checkEuqalValue(password,confirm_password,  "Mật khẩu nhắc lại")){
					 userRegistor(email, password);
				 }
			 },
			 "Hủy bỏ": function() {
				 $( this ).dialog( "close" );
			 }
		 }
	 });
	 
	 // news popup
	 $( "#news-dialog-form" ).dialog({
		 autoOpen: false,
		 height: 420,
		 width: 450,
		 modal: true,
		 buttons: {
			 "Đăng ký": function() {
				 var email = $("#news-email");
				 var fullname = $("#fullname");
				 if (checkEmail(email , "Email") && checkEmpty(fullname, "họ và tên")){
					 $( this ).dialog( "close" );
					 alert("Đăng ký nhận bản tin thành công");
				 }
			 },
			 "Hủy bỏ": function() {
				 $( this ).dialog( "close" );
			 }
		 }
	 });
	 
	 // search form on submit
	 $("#search-form").submit(function (){
		 $keyword = $("#keyword").val();
		 $keyword = utf8_encode($keyword);
		 window.location.href = "tim-kiem/" + $keyword + ".html";
		 return false;
	 });
});

/**
 * open popup login
 */
function openLoginPopup(){
	$( "#login-dialog-form" ).dialog( "open" );
}


/**
 * open popup register
 */
function openRegistorPopup(){
	
	$( "#register-dialog-form" ).dialog( "open" );
}


/**
 * open popup news
 */
function openNewsRecivePopup(){
	
	$( "#news-dialog-form" ).dialog( "open" );
}

/**
 * check empty val
 * @param obj
 * @param msg
 * @returns {Boolean}
 */
function checkEmpty(obj, msg){
	
	if (obj.val().length){
		obj.parent().removeClass('error');
		obj.parent().children('span').html("");
		return true;
		
	} else {
		obj.parent().addClass('error');
		obj.parent().children('span').html("Vui lòng nhập " + msg);
		return false;
	}
}

/**
 * check email format
 * @param obj
 * @param msg
 * @returns {Boolean}
 */
function checkEmail(obj, msg){
	
	if (checkEmpty(obj, msg)){
		var regexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
		if ( regexp.test(obj.val()) ){
			obj.parent().removeClass('error');
			obj.parent().children('span').html("");
			return true;
		} else {
			obj.parent().addClass('error');
			obj.parent().children('span').html(msg + " không chính xác");
			return false;
		}
	} else {
		return false;
	}
}

/**
 * check eual val
 * @param obj1
 * @param obj2
 * @param msg
 * @returns {Boolean}
 */
function checkEuqalValue(obj1, obj2, msg){
	if (obj1.val() == obj2.val() ){
		obj2.parent().removeClass('error');
		obj2.parent().children('span').html("");
		return true;
	} else{
		obj2.parent().addClass('error');
		obj2.parent().children('span').html(msg + " không khớp");
		return false;
	} 
}

/**
 * user login ajax
 * @param username
 * @param password
 */
function userLogin(username, password){
	$.ajax({
		url : "submit.php?ctrl=page-users&act=user-login",
		type : 'post',
		data : {'Username': username.val(), 'Password': password.val()},
		dataType : "json",
		success : function(data) {
			username.parent().removeClass('error');
			username.parent().children('span').html("");
			password.parent().removeClass('error');
			password.parent().children('span').html("");
			
			if(data.status == "fail"){
				if (data.Username == 'error'){
					username.parent().addClass('error');
					username.parent().children('span').html("Email không tồn tại");
				}
				if (data.Password == 'error') {
					password.parent().addClass('error');
					password.parent().children('span').html("Mật khẩu không chính xác");
				}
			} else {
				location.reload();
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Pegasus: có lỗi trong quá trình gửi dữ liệu \n Error Code: " + thrownError);
		}
	});
}

/**
 * user registor ajax
 * @param username
 * @param password
 */
function userRegistor(username, password){
	$.ajax({
		url : "submit.php?ctrl=page-users&act=user-registor",
		type : 'post',
		data : {'Username': username.val(), 'Password': password.val()},
		dataType : "json",
		success : function(data) {
			username.parent().removeClass('error');
			username.parent().children('span').html("");
			
			if(data.status == "fail"){
				if (data.Username == 'error'){
					username.parent().addClass('error');
					username.parent().children('span').html("Email đã tồn tại");
				} else {
					alert("Có lỗi sảy ra trong quá trình kết nối");
				}
			} else {
				alert("Đăng ký thành công");
				location.reload();
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Pegasus: có lỗi trong quá trình gửi dữ liệu \n Error Code: " + thrownError);
		}
	});
}

/**
 * load login box
 */
function loadLoginBox(){
	
	$.ajax({
		url : "submit.php?ctrl=page-users&act=check-login",
		type : 'post',
		data : {'Username': "0"},
		dataType : "json",
		success : function(data) {
			
			if(data.status == "ok"){
				var userBox = "<a href='javascript:showSettingControl()' class='user-setting'><span>"+ data.Username +"</span><span class='icon user-setting-icon'></span></a>"+
				    			"<div class='user-control'>"+
				    			"	<a href='#'> Chỉnh sửa thông tin</a>"+
				    			"	<a href='#'> Đổi mật khẩu</a>"+
				    			"	<a href='javascript:userLogout()' class='logout-link'> Đăng xuất</a>"+
				    			"</div> ";
				$("#user-box").html(userBox);
			} else {
				$("#user-box").html("<a href='javascript:openRegistorPopup()'>Đăng ký nhanh</a> | <a href='javascript:openLoginPopup()'>Đăng nhập</a>");
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Pegasus: có lỗi trong quá trình gửi dữ liệu \n Error Code: " + thrownError);
		}
	});
	
}

/**
 * log out function
 */
function userLogout(){
	$.ajax({
		url : "submit.php?ctrl=page-users&act=user-logout",
		type : 'post',
		data : {'Username': "0"},
		dataType : "json",
		success : function(data) {
			
			if(data.status == "ok"){
				location.reload();
			} else {
				alert("Có lỗi sảy ra trong quá trình kết nối");
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Pegasus: có lỗi trong quá trình gửi dữ liệu \n Error Code: " + thrownError);
		}
	});
}

/**
 * 
 */
function showSettingControl(){
	if (! $(".user-setting").hasClass('active')){
		$(".user-control").slideDown();
		$(".user-setting").addClass('active');
	}
}

// user control popup
$(document).ready(function() {
	
	// load user box
	loadLoginBox();
	
    $(".user-setting").click(function(e) {          
		e.preventDefault();
		if (! $(this).hasClass('active')){
			$(".user-control").slideDown();
			$(this).addClass('active');
		}
    });
	
	$(".user-control").mouseup(function() {
		return false;
	});
	
	$(".user-setting").mouseup(function() {
		return false;
	});
	
	$(document).mouseup(function(e) {
		$(".user-control").slideUp();
		$(".user-setting").removeClass('active');
	});			
	
});

/**
 * UTF-8 encode function
 * @param argString
 * @returns {String}
 */
function utf8_encode (argString) {
	  
	argString = argString.replace(/20/gi, "+");
	return argString.replace(/ /gi, "+"); 
	
}



